import { makeMap } from './util'
import { debounce } from 'lodash-es'

// 存储指令所需参数
let eventParams = {}
// 支持事件对象
const hasEventKey = makeMap('click,dblclick,keyup,keydown,keypress,mouseup,mousedown,mouseover,mouseleave,scroll')
const directives = {
  mounted(el, binding) {
    let defaultConfig = initEventParams(binding);
    eventParams = defaultConfig;
    bindElementEvent(el, binding.value)
  },
  updated(el, binding) {
    let defaultConfig = initEventParams(binding);
    eventParams = defaultConfig;
    bindElementEvent(el, binding.value)
  },
}

// 初始化指令参数
function initEventParams(binding) {
  let defaultConfig = {
    fun: '',
    event: 'click',
    args: '',
    wait: 3000,
    modifiers: {}
  }
  let modifierList = Object.keys(binding.modifiers).filter(key => binding.modifiers[key])
  defaultConfig.modifiers = binding.modifiers
  if (modifierList.length > 0) {
    // @ts-ignore
    let eventArr = modifierList.filter(vv => hasEventKey(vv))
    defaultConfig.event = eventArr.length === 0 ? 'click' : modifierList[0]
  }
  if (isObject(binding.value)) {
    Object.assign(defaultConfig, binding.value)
  } else if (isFunction(binding.value)) {
    defaultConfig.fun = binding.value
  }
  return defaultConfig
}

function bindElementEvent(el, context) {
  // @ts-ignore
  let { event, args, wait, modifiers } = eventParams

  if (!isFunction(context)) {
    return
  }
  let fireEvents = {
    leading: true,
    trailing: false
  }
  if (modifiers.before) {
    fireEvents = {
      leading: true,
      trailing: false
    }
  }
  if (modifiers.all) {
    fireEvents = {
      leading: true,
      trailing: true
    }
  }
  el[`on${event}`] = debounce(handleBindingEvent, wait, fireEvents)

  function handleBindingEvent(e) {
    if (modifiers.stop) e.stopPropagation();
    if (modifiers.prev) e.preventDefault();
    context.call(null, e, args);
  }

}

export default directives
